import { createRouter, createWebHistory, createWebHashHistory, type RouteLocationNormalized, type NavigationGuardNext } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useStore, type Store } from 'vuex'
import { SurveyPermissions } from '@/management/utils/types/formsTypes'
// import { analysisTypeMap } from '@/management/config/analysisConfig'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/src/message.scss'
import * as cnt from '@/management/utils/constant'
import { hasIntersection } from '@/management/utils/index'
import NProgress from "@/utils/nprogress";
import { initDynamicRouter } from "./modules/dynamicRouter.js";

const mode = import.meta.env.VITE_ROUTER_MODE;

/**
 * @description 📚 路由参数配置简介
 * @param path ==> 路由菜单访问路径
 * @param name ==> 路由 name (对应页面组件 name, 可用作 KeepAlive 缓存标识 && 按钮权限筛选)
 * @param redirect ==> 路由重定向地址
 * @param component ==> 视图文件路径
 * @param meta ==> 路由菜单元信息
 * @param meta.needLogin ==> 是否需要登录,
 * @param meta.roles ==> 角色权限控制,
 * @param meta.permissions ==> 角色权限控制
 * @param meta.icon ==> 菜单和面包屑对应的图标
 * @param meta.title ==> 路由标题 (用作 document.title || 菜单的名称)
 * @param meta.activeMenu ==> 当前路由为详情页时，需要高亮的菜单
 * @param meta.isLink ==> 路由外链时填写的访问地址
 * @param meta.isHide ==> 是否在菜单中隐藏 (通常列表详情页需要隐藏)
 * @param meta.isFull ==> 菜单是否全屏 (示例：数据大屏页面)
 * @param meta.isAffix ==> 菜单是否固定在标签页中 (首页通常是固定项)
 * @param meta.noSave ==> 菜单是否固定在标签页中 (首页通常是固定项)
 * @param meta.isKeepAlive ==> 当前路由是否缓存
 * */
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/forms'
  },
  // 活动
  {
    path: '/forms',
    name: 'forms',
    component: () => import('../pages/list/index.vue'),
    meta: {
      needLogin: true,
      title: '活动',
      isAffix: true
    }
  },
  {
    path: '/forms/:id/edit',
    meta: {
      needLogin: true,
      roles: cnt.ROLE_TEACHER_MANAGER,
      permissions: [SurveyPermissions.SurveyManage]
    },
    name: 'FormsEdit',
    component: () => import('../pages/edit/index.vue'),
    children: [
      {
        path: '',
        meta: {
          needLogin: true
        },
        name: 'FormsEditPage',
        component: () => import('../pages/edit/pages/edit/index.vue'),
        children: [
          {
            path: '',
            name: 'FormsEditIndex',
            meta: {
              needLogin: true
            },
            component: () => import('../pages/edit/pages/edit/QuestionEditPage.vue')
          },
        ]
      },
      {
        path: 'setting',
        name: 'FormsEditSetting',
        meta: {
          needLogin: true
        },
        component: () => import('../pages/edit/pages/setting/index.vue')
      },
      {
        path: 'skin',
        meta: {
          needLogin: true
        },
        component: () => import('../pages/edit/pages/skin/index.vue'),
        children: [
          {
            path: '',
            name: 'FormsSkinSetting',
            meta: {
              needLogin: true
            },
            component: () => import('../pages/edit/pages/skin/ContentPage.vue')
          },
          {
            path: 'result',
            name: 'FormsEditResultConfig',
            meta: {
              needLogin: true
            },
            component: () => import('../pages/edit/pages/skin/ResultPage.vue')
          }
        ]
      }
    ]
  },
  {
    path: '/forms/:id/publish',
    meta: {
      needLogin: true,
    },
    name: 'FormsPublish',
    component: () => import('../pages/publish/index.vue'),
    children: [
      {
        path: '',
        name: 'FormsPublishs',
        meta: {
          needLogin: true
        },
        component: () => import('@/management/pages/preview/index.vue'),
        children: [
          {
            path: '',
            name: 'FormsPublishPage',
            meta: {
              needLogin: true
            },
            component: () => import('@/render/pages/RenderPage.vue')
          },
          {
            path: 'success',
            name: 'previewSuccessPage',
            meta: {
              needLogin: true
            },
            component: () => import('@/render/pages/SuccessPage.vue')
          },
          {
            path: 'error',
            name: 'previewErrorPage',
            meta: {
              needLogin: true
            },
            component: () => import('@/render/pages/ErrorPage.vue')
          }
        ]
      },
      {
        path: 'setting',
        name: 'FormsPublishSetting',
        meta: {
          needLogin: true
        },
        component: () => import('../pages/publish/pages/setting/index.vue')
      },
      {
        path: 'analysis',
        name: 'FormsPublishAnalysis',
        meta: {
          needLogin: true,
          permissions: [SurveyPermissions.SurveyManage]
        },
        component: () => import('../pages/publish/pages/analysis/index.vue')
      }
    ]
  },
  {
    path: '/analysis/:id',
    meta: {
      needLogin: false,
    },
    name: 'ResultAnalysis',
    component: () => import('../pages/analysis/AnalysisPage.vue'),
    children: [
      {
        path: '',
        name: 'FormsResultAnalysis',
        meta: {
          needLogin: false,
          permissions: [SurveyPermissions.SurveyManage]
        },
        component: () => import('../pages/analysis/pages/SeparateStatisticsPage.vue')
      }
    ]
  },
  // 模板
  {
    path: '/templates',
    name: 'templates',
    component: () => import('../pages/templates/index.vue'),
    meta: {
      needLogin: true,
      roles: cnt.ROLE_MANAGERS,
      title: '模板'
    }
  },
  {
    path: '/appcenter',
    name: 'appcenter',
    component: () => import('../pages/appcenter/index.vue'),
    meta: {
      needLogin: true,
      title: '应用'
    }
  },
  {
    path: '/appdetail',
    name: 'appdetail',
    component: () => import('../pages/appcenter/detail.vue'),
    meta: {
      needLogin: true,
      title: '应用详情',
      "isHide": true,
      "noSave": true,
    }
  },
  {
    path: '/organization',
    name: 'organization',
    component: () => import('../pages/organization/index.vue'),
    meta: {
      needLogin: true,
      roles: cnt.ROLE_TEACHER_MANAGER,
      title: '组织'
    }
  },
  // 登录
  {
    path: '/login',
    name: 'login',
    component: () => import('../pages/login/login.vue'),
    meta: {
      "icon": "",
      title: '登录',
      "isLink": "",
      "isHide": false,
      "isFull": true,
      "isAffix": false,
      "isKeepAlive": false,
      nosave: true
    }
  }
]

const router = createRouter({
  history: mode === 'hash' ? createWebHashHistory('/myactivity') : createWebHistory('/myactivity'),
  routes
})

router.beforeEach(async (to, from, next) => {
  const store = useStore();

  // 1.NProgress 开始
  NProgress.start();

  // 初始化用户信息

  // if (!store.state?.ecouser?.initialized && to.meta?.needLogin) {
  //   console.log('kaishilo')
  //   await store.dispatch('ecouser/init');
  // }
  // 更新页面标题
  if (to.meta?.title) {
    document.title = to.meta.title as string;
  }

  if (to.meta?.needLogin) {
    await handleLoginGuard(to, from, next, store);
  } else {
    if ((window as any).$app?.token || (window as any).$app?.user?.token && !(to.name as string)?.startsWith('preview') && store.state.ecouser?.initialized) {
      next({ name: 'forms' });
    } else {
      next();
    }
  }
});

async function handleLoginGuard(to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext, store: Store<any>) {
  if (store.state.ecouser?.authorized ||  (window as any).$app.token || (window as any).$app?.user?.token) {
    await initDynamicRouter(store);
    next();
  } else {
    next({
      name: 'login',
      query: { redirect: encodeURIComponent(to.path) },
    });
  }
}

async function handlePermissionsGuard(to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext, store: Store<any>) {
  const currFormId = to?.params?.id || ''
  const prevFormId = from?.params?.id || ''
  // 存储 routerName 做按钮权限筛选
  store.dispatch('layouts/setRouteName', to.name);
  console.log('333333')
  // 如果跳转页面不存在formId 或者不需要页面权限，则直接跳转
  if (to.meta.roles) { // 页面角色（模板需要管理员，编辑需要老师和管理员）
    console.log('444444')
    const userroles: Array<string> = (store.state?.ecouser?.roleIdList || (window as any).$app?.user?.roleIdList || [])
    if (!hasIntersection(to.meta.roles as string[], userroles)) {
      console.log('55555555')
      ElMessage.warning('您没有该活动的相关权限');
      // (window as any).$app.delAuth(true)
      next({ name: 'forms' });
    } else {
      console.log('66666666')
      if (!store.getters['layouts/authMenuListGet']?.length) {
        console.log('77777777')
        await initDynamicRouter(store);
        return next({ ...to, replace: true });
      }
      next();
    }
  } else {
    console.log('8888888')
    if (!to.meta.permissions || !currFormId) {
      console.log('999999999')
      // 如果没有动态菜单列表，就重新请求菜单列表并添加动态路由
      if (!store.getters['layouts/authMenuListGet']?.length) {
        console.log('100000000')
        await initDynamicRouter(store);
        return next({ ...to, replace: true });
      }
      next()
    } else {
      console.log('110000000')
      // 如果跳转编辑页面，且跳转页面和上一页的formId不同，判断是否有对应页面权限
      if (currFormId !== prevFormId) {
        console.log('120000000')
        await store.dispatch('fetchCooperPermissions', currFormId)
        if (store.state.cooperPermissions.length === 0 || hasRequiredPermissions(to.meta.permissions as string[], store.state.cooperPermissions)) {
          console.log('130000000')
          next();
        } else {
          console.log('140000000')
          ElMessage.warning('您没有该活动的相关共享权限');
          next({ name: 'forms' });
        }
      } else {
        console.log('150000000')
        next();
      }
    }
  }

}

function hasRequiredPermissions(requiredPermissions: string[], userPermissions: string[]) {
  return requiredPermissions.some(permission => userPermissions.includes(permission));
}

/**
 * @description 路由跳转结束
 * */
router.afterEach(() => {
  NProgress.done();
});

export default router
